        
package com.dkm.modules.wx.file.controller;

import com.dkm.commons.BaseController;
import com.dkm.commons.Response;
import com.dkm.constant.CommonErrorEnum;
import com.dkm.constant.Constant;
import com.dkm.modules.wx.file.model.FileModel;
import com.dkm.modules.wx.file.service.FileService;
import com.dkm.util.IdGen;
import com.dkm.util.qiniu.QiNiuUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName FileController
 * @Description: 文件上传控制器
 * @Author yangbin
 * @Date 2019-09-05 23:09
 * @Version V1.0
 **/
@Api(tags="（公共）上传")
@Controller
@RequestMapping("/file")
public class FileController extends BaseController {

    @Autowired
    private Environment env;

    private final static Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private FileService fileService;
    @Value("${QiNiu-URL}")
    private String QiNiuUrl;


     /**
      * @MethodName:
      * @Description: 文件上传
      * @Param:
      * @Return:
      * @Author: yangbin
      * @Date: 2019/9/5
     **/
    @PostMapping("/uploadFile")
    public Response uploadFile(MultipartFile file, String business) {
        if (Objects.isNull(file) || file.isEmpty()) {
            logger.error("上传文件为空");
            return Response.error(CommonErrorEnum.UPLOAD_FAILED);
        }
        //文件名
        String realName = file.getOriginalFilename();
        //后缀名
        String suffix = realName.substring(realName.lastIndexOf("."));
        //生成新文件名
        String file_id = IdGen.uuid();
        String FileName =file_id+suffix;
        //取用户登录名
        String userName = (String) super.getSession().getAttribute(Constant.USER_SESSION_KEY);

        FileModel fileModel = new FileModel();
        fileModel.setFileName(FileName);
        fileModel.setId(file_id);
        fileModel.setFileRealName(realName);
        fileModel.setBusiness(business);
        fileModel.setCreateTime(new Date());
        fileModel.setCreateBy(userName);

        //上传
        fileService.uploadFile(file,fileModel);
        //返回文件Id
        return Response.ok(file_id);
    }

     @ApiOperation("上传图片到七牛云")
     @PostMapping("/uploadImg")
     @ResponseBody
     @ApiImplicitParam(paramType = "header",name = "token",value = "身份认证Token")
     public Response uploadImg(@ApiParam(value = "图片") MultipartFile file,
                              @ApiParam (value = "业务区分")@RequestParam("business") String business){
        logger.info("上传图片");
         String filePath = env.getProperty("upload-file-path");
         //文件名
         String realName = file.getOriginalFilename();
         //后缀名
         String suffix = realName.substring(realName.lastIndexOf("."));

         try {
             //生成新文件名
             String fileId = IdGen.uuid();
             String fileName =fileId+suffix;
             //上传图片到七牛云
             InputStream is = file.getInputStream();
             int r = QiNiuUtil.getInstance().uploadFile(is,fileName);
             if (r==1){

                //保存文件数据
                 FileModel fileModel = new FileModel();
                 fileModel.setFileName(fileName);
                 fileModel.setId(fileId);
                 fileModel.setFileRealName(realName);
                 fileModel.setBusiness(business);
                 fileModel.setCreateTime(new Date());
                 //取用户登录名
                 String userName = (String) super.getSession().getAttribute(Constant.USER_SESSION_KEY);
                 fileModel.setCreateBy(userName);

                 fileModel.setFileUrl(QiNiuUrl+fileName);

                 Map<String,String> result = new HashMap<>();
                 result.put("imgID",fileId);

                 //存库
                 fileService.insertFileInfo(fileModel);

                 logger.info("上传成功");
                 return Response.ok(result);
             }
            return Response.error();
         } catch (Exception e) {
             e.printStackTrace();
             logger.info("上传失败");
             return Response.error();
         }


    }
}
